<template>
  <div class="el-dialog-25">
    <el-dialog v-model="props.showInfoDialog" title="完善个人信息后才能开启社团之旅" :show-close="false" :close-on-press-escape="false"
      :close-on-click-modal="false">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="账号：" prop="username" class="el-form-item-full">
          <el-input v-model="ruleForm.username" disabled />
        </el-form-item>
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="性别：" prop="gender" class="el-form-item-full">
          <el-select v-model="ruleForm.gender" class="m-2" placeholder="请选择性别">
            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="学号：" prop="stuCode">
          <el-input v-model="ruleForm.stuCode" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="学院：" prop="college" required clearable class="el-form-item-full">
          <el-select v-model="ruleForm.college" class="m-2" placeholder="请选择学院" @change="selectCollege">
            <el-option v-for="item in collegeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业：" prop="major" class="el-form-item-full">
          <el-select v-model="ruleForm.major" class="m-2" placeholder="请选择专业" :key="ruleForm.college"
            :disabled="!ruleForm.college">
            <el-option v-for="item in majorOptions" :key="item.id + item.name" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="年级：" prop="grade" class="el-form-item-full">
          <el-select v-model="ruleForm.grade" class="m-2" placeholder="请选择年级">
            <el-option v-for="item in gradeOptions" :key="item.id + item.name" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm(ruleFormRef)" class="btn-white">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)" class="btn-green">
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
// useUserStoreHook
import { useUserStoreHook } from "@/store/modules/user";
import { usePublicStoreHook } from "@/store/modules/public";
import { fetchPutUserInfo } from '@/api/user'
const userStore = useUserStoreHook()
const publicStore = usePublicStoreHook()

const props = defineProps({
  showInfoDialog: Boolean,  // 控制弹框的显示与隐藏
  // 父组件传过来的表单数据
  formData: {
    type: Object,
  }
});

const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  id: userStore.userInfo.id,
  username: userStore.userInfo.username, // 名称
  name: "", // 姓名
  gender: undefined, // 性别
  stuCode: '', // 学号
  college: undefined, // 学院
  major: undefined, // 专业
  grade: undefined, // 年级
  phone: "", // 手机号
});

const rules = reactive<FormRules>({
  username: [{ required: true, trigger: "change" }],
  name: [{ required: true, message: "请输入姓名", trigger: "change" }],
  gender: [
    { required: true, message: "请选择性别", trigger: "change" },
  ],
  stuCode: [
    { required: true, message: "请输入学号", trigger: "change" },
  ],
  college: [
    { required: true, message: "请输入学院", trigger: "change" },
  ],
  major: [
    { required: true, message: "请输入专业", trigger: "change" },
  ],
  grade: [
    { required: true, message: "请输入年级", trigger: "change" }
  ],
  phone: [{ required: true, message: "请输入手机号", trigger: "change" }],
});

/**
 * 提交表单
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      fetchPutUserInfo(ruleForm).then((res) => {
        if (Number(res.code) === 200) {
          ElMessage({
            type: 'success',
            message: '填写成功，欢迎来到社团联',
          })
          emit("closeDialog");
        }
      })
    } else {
      ElMessage({
        type: 'warning',
        message: '请正确填写',
      })
    }
  });
};
const emit = defineEmits(["closeDialog", "openDialog"]);


/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  ElMessageBox.confirm(
    '未完善个人信息将退出登录，是否确定？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      /** 此处会触发两次，待优化----------------------------------------------------------------------------------------------------------------------------- */
      // 关闭弹框
      emit("closeDialog");
      // 重置验证规则
      if (!formEl) return;
      formEl.resetFields();
      userStore.logout()
      ElMessage({
        type: 'success',
        message: '退出成功',
      })
    })
    .catch(() => {
      emit("openDialog");
    })

};

// 男女选择器数据
const genderOptions = [
  {
    value: 0,
    label: '男',
  },
  {
    value: 1,
    label: '女',
  },
]

// 学院选择数据
let collegeOptions = reactive([{
  id: 1,
  name: '计算机学院'
}])
// 专业数据
let allMajorOptions = reactive([{
  id: 1,
  name: '通信专业',
  collegeId: 0
}])
// 年级数据
let gradeOptions = reactive([{}])

let majorOptions: { id: number; name: string; college_id: number; }[] = reactive([{
  id: 1,
  name: '通信专业',
  college_id: 0
}])
const selectCollege = () => {
  ruleForm.major = undefined;
  majorOptions = []
  console.log(allMajorOptions)
  allMajorOptions.map((item) => {
    if (Number(item.collegeId) === Number(ruleForm.college)) {
      majorOptions.push(item)
    }
  })
}
onMounted(() => {
  collegeOptions = publicStore.collegeList
  gradeOptions = publicStore.gradeList
  allMajorOptions = publicStore.majorList
})
</script>

<style scoped lang="scss"></style>
